
import 'package:flutter/cupertino.dart';
import 'package:hx_demo_example/data/service_data.dart';

import '../message_model/em_message.dart';
import 'customer_service_state.dart';

class CustomerServicePageProvider extends ChangeNotifier {


  final state = CustomerServiceState();


  void upDataMessage(List? value){
    if(value == null)return;
    for (var element in value) {
      state.messages.insert(0,  EMMessage.fromJson(element));
    }
    notifyListeners();
  }


  /// 发送消息
  void sendMessage(){
    ChatService.sendTextMessage(text: state.textEditController.text,).then((value) {
      print(value);
      upDataMessage((value is List)?value:[value]);
    });
    changeSendBtn(false);
  }

  ///是否显示发送按钮
  changeSendBtn(bool show) {

    if(show == false){
      state.textEditController.text = "";
    }
    state.isShowSend = show;
    state.textFieldHeight = 36;
    notifyListeners();
  }


  ///动态计算textfield 高度
  changeTextFieldHeight(String content,{BuildContext? context}){

    state.textFieldHeight = _calculateTextFieldHeight(
        context: context,
        value: content);
    notifyListeners();
  }

  ///改变底部Widget
  changeKeyBoard(bool show,{bool cancelKeyBode = false}){
    Future.delayed(const Duration(milliseconds: 200),(){
      if(cancelKeyBode){
        state.isShowTools = show==true?false:show;
        state.isShowKeyboard =!show;
      }else{
        state.isShowTools = show;
      }
      notifyListeners();
    });
  }


  ///隐藏
  void changeTools({bool showTool = false,bool isKeyBody = false}) {
    if(isKeyBody){
      state.textFieldNode.requestFocus();
    }else{
      state.textFieldNode.unfocus();
      Future.delayed(const Duration(milliseconds: 250),(){
        changeKeyBoard(showTool);
        notifyListeners();
      });

    }
  }


  ///底部tab-Height-Padding
  double paddingHeight(){
    bool showKeyBoard = (state.isShowKeyboard == true || state.isShowTools == true);
      return showKeyBoard ?9 :state.bottomHeight + 6.5;
  }


  double _calculateTextFieldHeight({BuildContext? context,String? value}) {
    final textSpan = TextSpan(
      text: value,
      style: const TextStyle(fontSize: 16.0),
    );
    final textPainter = TextPainter(
      text: textSpan,
      textDirection: TextDirection.ltr,
      maxLines: 10,
    )
      ..layout(maxWidth: MediaQuery
          .of(context!)
          .size
          .width - 90);
    print(textPainter.height);
    return textPainter.height;
  }


  Future<String?> listenerEvent() async {
    var ev ;
    state.streamSubscription = state.eventChannel.receiveBroadcastStream().listen((event) {
      ev = event;
      upDataMessage([ev]);
      print("=======$ev========$event");
    });
    return ev;
  }

}
